// 蜂窝蜜造平台生成代码，如手工更改，请添加到 .beeignore 忽略生成

package com.fowo.api.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fowo.api.common.config.CacheConfig;
import com.fowo.api.common.excel.CustomExcelExport;
import com.fowo.api.common.excel.CustomExcelHandler;
import com.fowo.api.common.excel.ExcelConfig;
import com.fowo.api.common.excel.TemplateModelBuildEventListener;
import com.fowo.api.common.model.ImportRow;
import com.fowo.api.common.model.JoinModel;
import com.fowo.api.common.model.OptionItem;
import com.fowo.api.common.model.RException;
import com.fowo.api.common.util.ContextHolder;
import com.fowo.api.common.util.DateUtils;
import com.fowo.api.common.util.ResponseUtils;
import com.fowo.api.common.util.SheetUtils;
import com.fowo.api.entity.CostSupplementForm;
import com.fowo.api.flow.entity.WorkFlow;
import com.fowo.api.flow.service.WorkFlowService;
import com.fowo.api.mapper.CostSupplementFormMapper;
import com.fowo.api.mapper.CostSupplementFormSubtableMapper;
import com.fowo.api.mapper.WarehouseMapper;
import com.fowo.api.model.cost.supplement.form.CostSupplementFormAddCostSupplementFormAction;
import com.fowo.api.model.cost.supplement.form.CostSupplementFormDelete1Action;
import com.fowo.api.model.cost.supplement.form.CostSupplementFormExamineAndApproveAction;
import com.fowo.api.model.cost.supplement.form.CostSupplementFormExcelPo;
import com.fowo.api.model.cost.supplement.form.CostSupplementFormHandleAction;
import com.fowo.api.model.cost.supplement.form.CostSupplementFormImportPo;
import com.fowo.api.model.cost.supplement.form.CostSupplementFormItemVo;
import com.fowo.api.model.cost.supplement.form.CostSupplementFormSearchParamPo;
import com.fowo.api.model.cost.supplement.form.CostSupplementFormVo;
import com.fowo.api.model.cost.supplement.form.constant.CostSupplementFormDocumentStatusEnums;
import com.fowo.api.model.cost.supplement.form.constant.CostSupplementFormTypeEnums;
import com.fowo.api.model.cost.supplement.form.subtable.CostSupplementFormSubtableItemVo;
import com.fowo.api.model.cost.supplement.form.subtable.CostSupplementFormSubtableItemVoPages;
import com.fowo.api.model.cost.supplement.form.subtable.CostSupplementFormSubtableSearchParamPo;
import com.fowo.api.model.warehouse.WarehouseItemVo;
import com.fowo.api.model.warehouse.WarehouseSearchParamPo;
import com.fowo.api.service.CostSupplementFormService;
import com.fowo.api.service.CostSupplementFormSubtableService;
import com.fowo.api.sys.annotation.DataActivity;
import com.fowo.api.sys.component.SysDataActivityAopHelper;
import com.fowo.api.sys.entity.SysFile;
import com.fowo.api.sys.entity.SysImportTemplate;
import com.fowo.api.sys.entity.enums.SysDataActivityAction;
import com.fowo.api.sys.service.FileService;
import com.fowo.api.sys.service.SysImportTemplateService;
import com.fowo.api.user.model.JwtUserInfo;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * 成本补录单 服务实现类
 * @author 蜂窝蜜造平台 配置人：汤帅杰，辜天飞
 */
@Service
@Slf4j
@DS("ds24")
public class CostSupplementFormServiceImpl
  extends ServiceImpl<CostSupplementFormMapper, CostSupplementForm>
  implements CostSupplementFormService {

  /** 引用字段排序字段名转换信息 */
  public static final Map<String, String> SORT_FIELD_MAP = new HashMap<>() {
    {
      put("warehouseName", "w.`name`");
    }
  };
  // 导出时单次查询最大记录数
  protected static final int EXPORT_QUERY_MAX_SIZE = 1000;
  // 支持导出的最大记录数(1048576 为 Excel 支持的最大行数)
  protected static final long EXPORT_MAX_SIZE = 1048575;

  /**
   * 服务自引用，用于调用服务方法时包括 AOP 处理
   */
  @Resource
  protected CostSupplementFormService self;

  @Resource
  protected CostSupplementFormSubtableService costSupplementFormSubtableService;

  @Resource
  protected WarehouseMapper warehouseMapper;

  @Resource
  protected FileService fileService;

  @Resource
  protected SysImportTemplateService importTemplateService;

  @Resource
  private CustomExcelExport customExcelExport;

  @Resource
  protected WorkFlowService workFlowService;

  @Autowired(required = false)
  protected CostSupplementFormHandleAction costSupplementFormHandleAction;

  @Autowired(required = false)
  protected CostSupplementFormAddCostSupplementFormAction costSupplementFormAddCostSupplementFormAction;

  @Autowired(required = false)
  protected CostSupplementFormExamineAndApproveAction costSupplementFormExamineAndApproveAction;

  @Autowired(required = false)
  protected CostSupplementFormDelete1Action costSupplementFormDelete1Action;

  @Resource
  protected Validator validator;

  /**
   * 创建成本补录单
   * @param model 成本补录单
   * @return 新数据的主键
   */
  @DataActivity(action = SysDataActivityAction.Add)
  @Transactional(rollbackFor = Exception.class)
  @Override
  public Long create(CostSupplementFormVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    CostSupplementForm entity = new CostSupplementForm();
    BeanUtils.copyProperties(model, entity);
    entity.setCreateTime(new Date());
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setCreateUser(currentUser.getUserId());
      entity.setLastUpdateUser(currentUser.getUserId());
    }

    if (model.getType() == null) {
      entity.setType("0");
    }
    if (this.save(entity)) {
      model.setId(entity.getId());
      updateAllChilds(model);
      return entity.getId();
    }
    throw new Exception("成本补录单保存失败");
  }

  /**
   * 更新所有子表
   * @param model 成本补录单
   */
  protected void updateAllChilds(CostSupplementFormVo model) throws Exception {
    if (model.getSupplementaryProduct() != null) {
      costSupplementFormSubtableService.saveAllByParentCostSupplementForm(
        model.getId(),
        model.getSupplementaryProduct()
      );
    }
  }

  /**
   * 更新成本补录单
   * @param model 成本补录单
   * @return 更新是否成功
   */
  @DataActivity(action = SysDataActivityAction.Modified)
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean update(CostSupplementFormVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    CostSupplementForm entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("成本补录单不存在");
    }
    BeanUtils.copyProperties(
      model,
      entity,
      "id",
      "createTime",
      "createUser",
      "lastUpdateTime",
      "lastUpdateUser"
    );
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setLastUpdateUser(currentUser.getUserId());
    }
    if (this.updateById(entity)) {
      updateAllChilds(model);
      return true;
    }
    return false;
  }/**
   * 更新成本补录单（带空值）
   * @param model 成本补录单
   * @return 更新是否成功
   */

  @DataActivity(action = SysDataActivityAction.Modified)
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean updateForEdit(CostSupplementFormVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    CostSupplementForm entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("成本补录单不存在");
    }
    model.setLastUpdateTime(new Date());
    if (currentUser != null) {
      model.setLastUpdateUser(currentUser.getUserId());
    }
    boolean isOk = new LambdaUpdateChainWrapper<>(baseMapper)
      .set(CostSupplementForm::getType, model.getType())
      .set(CostSupplementForm::getWarehouse, model.getWarehouse())
      .set(CostSupplementForm::getRemark, model.getRemark())
      .set(CostSupplementForm::getLastUpdateTime, model.getLastUpdateTime())
      .set(CostSupplementForm::getLastUpdateUser, model.getLastUpdateUser())
      .set(CostSupplementForm::getDocumentStatus, model.getDocumentStatus())
      .eq(CostSupplementForm::getId, model.getId())
      .update();
    if (isOk) {
      updateAllChilds(model);
    }
    return isOk;
  }

  /**
   * 是否走导出中心
   */
  @Override
  public boolean getBackgroundExportFlag(
    CostSupplementFormSearchParamPo search
  ) {
    return false;
  }

  /**
   * 批量删除指定主键列表关联的所有子表数据(此方法不包括事务，必须由其它已包括事务的方法调用)
   */
  protected void batchDeleteChilds(List<Long> ids) throws Exception {
    // 处理子表字段 补录产品(supplementaryProduct) 对应的对象
    CostSupplementFormSubtableSearchParamPo supplementaryProductSearchParam =
      new CostSupplementFormSubtableSearchParamPo();
    supplementaryProductSearchParam.setDisableDataPremissions(true);
    supplementaryProductSearchParam.setParentCostSupplementFormInList(ids);
    CostSupplementFormSubtableMapper localCostSupplementFormSubtableMapper =
      ContextHolder
        .getApplicationContext()
        .getBean(CostSupplementFormSubtableMapper.class);
    supplementaryProductSearchParam.applySqlSegments();
    List<Long> supplementaryProductIdList =
      localCostSupplementFormSubtableMapper.searchIds(
        supplementaryProductSearchParam
      );
    if (!supplementaryProductIdList.isEmpty()) {
      CostSupplementFormSubtableService localCostSupplementFormSubtableService =
        ContextHolder
          .getApplicationContext()
          .getBean(CostSupplementFormSubtableService.class);
      localCostSupplementFormSubtableService.batchDelete(
        supplementaryProductIdList
      );
    }
  }

  /**
   * 删除成本补录单
   * @param id 成本补录单的主键
   * @return 删除是否成功
   */
  @DataActivity(action = SysDataActivityAction.Del)
  @Override
  public boolean delete(Long id) throws Exception {
    batchDeleteChilds(Collections.singletonList(id));
    return this.removeById(id);
  }

  /**
   * 批量删除成本补录单
   * @param ids 成本补录单的主键列表
   * @return 删除是否成功
   */
  @DataActivity(action = SysDataActivityAction.Del)
  @Override
  public boolean batchDelete(List<Long> ids) throws Exception {
    batchDeleteChilds(ids);
    return baseMapper.deleteBatchIds(ids) > 0;
  }

  /**
   * 导入单行处理
   * @param row 要导入的行
   * @param rowNumber 所在行号
   * @param vo 输出VO,可空
   * @param variables 变量池，用于在一次导入过程中保存临时信息
   * @param allowOverrides 允许覆盖
   * @return 导入行对象
   */
  protected ImportRow<CostSupplementFormImportPo> excelToImportRow(
    CostSupplementFormImportPo row,
    Integer rowNumber,
    CostSupplementFormVo vo,
    Map<String, Object> variables,
    boolean allowOverrides
  ) {
    ImportRow<CostSupplementFormImportPo> ir =
      new ImportRow<CostSupplementFormImportPo>();
    ir.setRowNumber(rowNumber);
    ir.setRow(row);
    if (SheetUtils.isAllFieldsEmpty(row)) {
      ir.setEmptyRow(true);
      ir.addError("", "空行");
      return ir;
    }
    final Set<ConstraintViolation<CostSupplementFormImportPo>> validate =
      validator.validate(row);
    boolean isOutputVo = vo != null;
    if (!isOutputVo) {
      vo = new CostSupplementFormVo();
    }
    BeanUtils.copyProperties(row, vo);
    // 收集基本校验错误
    ir.initErrors(validate, CostSupplementFormImportPo.class);

    // 一般数据处理
    if (StringUtils.hasText(row.getType())) {
      vo.setType(CostSupplementFormTypeEnums.toValue(row.getType()));
      if (vo.getType() == null) {
        ir.addError("type", "类型只能是：“入库成本”");
      }
    }
    if (StringUtils.hasText(row.getDocumentStatus())) {
      vo.setDocumentStatus(
        CostSupplementFormDocumentStatusEnums.toValue(row.getDocumentStatus())
      );
      if (vo.getDocumentStatus() == null) {
        ir.addError(
          "documentStatus",
          "单据状态只能是：“待审批”, “已处理”, “已驳回”"
        );
      }
    }
    // 处理关联字段“仓库”
    if (
      !SheetUtils.isBlank(row.getWarehouseName()) &&
      SheetUtils.isBlank(row.getWarehouse())
    ) {
      WarehouseSearchParamPo warehouseSearchParam =
        new WarehouseSearchParamPo();
      warehouseSearchParam.setLimit(2); // 最大只返回二行记录
      warehouseSearchParam.setNameEq(SheetUtils.trim(row.getWarehouseName()));
      warehouseSearchParam.applySqlSegments();
      List<WarehouseItemVo> warehouseMatches = warehouseMapper.search(
        warehouseSearchParam
      );
      if (warehouseMatches.size() == 0) {
        ir.addError("warehouseName", "未能在仓库列表中找到匹配的数据");
      } else if (warehouseMatches.size() > 1) {
        ir.addError(
          "warehouseName",
          "关联不唯一，在仓库列表中找到多个匹配的数据"
        );
      } else {
        vo.setWarehouse(warehouseMatches.get(0).getId());
      }
    }

    return ir;
  }

  /**
   * 导入预览
   * @param sysFile 已上传到系统的文件
   * @param templateId 要使用的模版编号
   * @param allowOverrides 允许覆盖
   */
  @Override
  public List<ImportRow<CostSupplementFormImportPo>> importPreview(
    SysFile sysFile,
    Long templateId,
    boolean allowOverrides
  ) throws Exception {
    SysImportTemplate importTemplate = null;
    if (templateId != null && templateId > 0) {
      importTemplate = importTemplateService.getById(templateId);
      if (importTemplate == null) {
        throw new RException("指定的模版不可用！");
      }
    }
    Map<String, Object> variables = new HashMap<>();

    // 标记由模版直接导入的字段集
    if (importTemplate != null) {
      variables.put(
        "IMPORT_FIELDS",
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .map(SysImportTemplate.Mapping::getField)
          .collect(Collectors.toSet())
      );
    }
    try (InputStream in = fileService.read(sysFile)) {
      List<ImportRow<CostSupplementFormImportPo>> rows = new ArrayList<>();

      // 读取 Excel 到 rows
      EasyExcel
        .read(in)
        .useDefaultListener(false)
        .registerReadListener(
          new TemplateModelBuildEventListener<>(
            CostSupplementFormImportPo.class,
            importTemplate
          ) {
            @Override
            public void invokeRow(
              CostSupplementFormImportPo row,
              AnalysisContext cxt
            ) {
              CostSupplementFormVo vo = new CostSupplementFormVo();
              ImportRow<CostSupplementFormImportPo> ir = excelToImportRow(
                row,
                cxt.readRowHolder().getRowIndex(),
                vo,
                variables,
                allowOverrides
              );
              if (ir.isEmptyRow()) {
                return;
              }
              if (allowOverrides) {
                // FIXME: 未在平台上配置此对象《作为导入唯一识别》的《逻辑分组》配置，无法处理更新模式
              }
              rows.add(ir);
            }
          }
        )
        .sheet()
        .doRead();

      return rows;
    }
  }

  /**
   * 完成导入
   * @param rows 预导入的行信息
   */
  @DataActivity(action = SysDataActivityAction.Import)
  @Transactional(rollbackFor = Exception.class)
  @Override
  public void importDone(
    List<ImportRow<CostSupplementFormImportPo>> rows,
    Long templateId
  ) throws Exception {
    SysImportTemplate importTemplate = null;
    if (templateId != null && templateId > 0) {
      importTemplate = importTemplateService.getById(templateId);
      if (importTemplate == null) {
        throw new RException("指定的模版不可用！");
      }
    }
    String sysImportBatchNo = StrUtil.concat(
      true,
      DateUtil.format(DateUtil.date(), DatePattern.PURE_DATETIME_MS_PATTERN),
      IdUtil.nanoId(4)
    );
    List<Long> importedIdList = new ArrayList<>();
    SysDataActivityAopHelper.clear();
    final SysDataActivityAopHelper.DataActivityAopContext context =
      SysDataActivityAopHelper.getOrCreateContext();
    Map<String, Object> variables = new HashMap<>();

    // 标记由模版直接导入的字段集
    if (importTemplate != null) {
      variables.put(
        "IMPORT_FIELDS",
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .map(SysImportTemplate.Mapping::getField)
          .collect(Collectors.toSet())
      );
    }
    for (int i = 0; i < rows.size(); i++) {
      ImportRow<CostSupplementFormImportPo> row = rows.get(i);
      Long updateId = row.getUpdateId();
      CostSupplementFormVo vo = new CostSupplementFormVo();
      row =
        excelToImportRow(row.getRow(), row.getRowNumber(), vo, variables, true);
      if (row.getErrors() != null && row.getErrors().size() > 0) {
        throw new RException(
          String.format(
            "第%d行（Excel第%d行）数据验证错误：%s",
            i + 1,
            row.getRowNumber(),
            row.getJoinErrorMessage()
          )
        );
      }
      if (updateId != null) {
        vo.setId(updateId);
      }
      SheetUtils.setSysImportTemplateName(
        vo,
        null == importTemplate ? "默认模板" : importTemplate.getTitle()
      );
      SheetUtils.setSysImportBatchNo(vo, sysImportBatchNo);
      if (updateId == null) {
        importedIdList.add(create(vo));
      } else {
        self.update(vo);
        importedIdList.add(vo.getId());
      }
    }
    context.getIdList().addAll(importedIdList);
  }

  /**
   * 导出
   * @param templateId 使用模版（可以是 null 或 0 表示系统默认导出模版）
   * @param search 查询条件
   */
  @DataActivity(action = SysDataActivityAction.Export)
  @Override
  public void export(
    Long templateId,
    CostSupplementFormSearchParamPo search,
    HttpServletResponse response
  ) throws Exception {
    if (templateId != null && templateId > 0) {
      SysImportTemplate sysImportTemplate = importTemplateService.getById(
        templateId
      );
      if (sysImportTemplate == null) {
        throw new RException("所选的导出模版不可用");
      }
      CustomExcelExport.CustomExcelExportOptions exportOptions =
        new CustomExcelExport.CustomExcelExportOptions();
      exportOptions.setImportTemplate(sysImportTemplate);
      exportOptions.setSearchParam(search);
      exportOptions.setMainService(this);
      exportOptions.addFieldMappingOption(
        "type",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            CostSupplementFormTypeEnums.toLabel((String) o)
          )
      );
      exportOptions.addFieldMappingOption(
        "warehouse",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((CostSupplementFormItemVo) r).getWarehouseName())
          )
      );
      exportOptions.addFieldMappingOption(
        "documentStatus",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            CostSupplementFormDocumentStatusEnums.toLabel((String) o)
          )
      );
      exportOptions.addStringFields(
        "orderNumber",
        "type",
        "warehouseName",
        "remark",
        "documentStatus"
      );

      String fileName = String.format(
        "成本补录单(%s).xlsx",
        DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
      );
      ResponseUtils.setAttachmentFileName(response, fileName);
      customExcelExport.run(exportOptions, response.getOutputStream());
      return;
    }
    search.setPageSize(EXPORT_QUERY_MAX_SIZE);
    int current = 1;
    List<CostSupplementFormExcelPo> items =
      new ArrayList<CostSupplementFormExcelPo>();
    while (true) {
      search.setCurrent(current);
      Page<CostSupplementFormItemVo> page = this.pageSearch(search);
      if (page.getTotal() > EXPORT_MAX_SIZE) {
        throw new RException("导出记录数超出限制！");
      }
      List<CostSupplementFormItemVo> list = page.getRecords();
      if (list.isEmpty()) {
        break;
      }
      for (CostSupplementFormItemVo item : list) {
        CostSupplementFormExcelPo excel = new CostSupplementFormExcelPo();
        BeanUtils.copyProperties(item, excel);
        excel.setType(CostSupplementFormTypeEnums.toLabel(item.getType()));
        excel.setDocumentStatus(
          CostSupplementFormDocumentStatusEnums.toLabel(
            item.getDocumentStatus()
          )
        );

        items.add(excel);
      }
      if (list.size() < EXPORT_QUERY_MAX_SIZE) {
        break;
      }
      current++;
    }

    String fileName = String.format(
      "成本补录单(%s).xlsx",
      DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
    );
    ResponseUtils.setAttachmentFileName(response, fileName);
    EasyExcel
      .write(response.getOutputStream())
      .registerWriteHandler(new CustomExcelHandler())
      .sheet()
      .head(CostSupplementFormExcelPo.class)
      .doWrite(items);
  }

  /**
   * 通过补录单号查询成本补录单主键(重复时返回最新的主键)
   */
  @Override
  public Long getIdByOrderNumber(String orderNumber) {
    return this.baseMapper.getIdByOrderNumber(orderNumber);
  }

  /**
   * 通过补录单号查询成本补录单多主键(重复时返回最新的主键)
   */
  @Override
  public List<Long> getIdsByOrderNumber(List<String> list) {
    return this.baseMapper.getIdsByOrderNumber(list);
  }

  /**
   * 通过成本补录单主键查询补录单号
   */
  @Override
  public String getOrderNumberById(Long id) {
    return this.baseMapper.getOrderNumberById(id);
  }

  /**
   * 通过成本补录单主键查询补录单号列表
   */
  @Override
  public List<String> getOrderNumberByIds(List<Long> ids) {
    List<Map<String, Object>> maps = this.baseMapper.getOrderNumberByIds(ids);
    // 将返回重新排列为输入相同顺序
    return ids
      .stream()
      .map(id -> {
        Optional<Map<String, Object>> optionalMap = maps
          .stream()
          .filter(map -> id.equals(map.get("id")))
          .findFirst();
        return optionalMap
          .map(stringObjectMap -> (String) stringObjectMap.get("orderNumber"))
          .orElse(null);
      })
      .collect(Collectors.toList());
  }

  /**
   * 获取详情
   * @param id 成本补录单的主键
   */
  @DataActivity(action = SysDataActivityAction.View)
  @Override
  public CostSupplementFormVo getVoById(Long id) throws Exception {
    CostSupplementFormVo vo = this.baseMapper.selectVoById(id);
    if (vo == null) {
      return null;
    }

    CostSupplementFormSubtableSearchParamPo supplementaryProductSearchParamPo =
      new CostSupplementFormSubtableSearchParamPo();
    supplementaryProductSearchParamPo.setParentCostSupplementForm(id);
    supplementaryProductSearchParamPo.applySqlSegments();
    vo.setSupplementaryProduct(
      costSupplementFormSubtableService.search(
        supplementaryProductSearchParamPo
      )
    );

    return vo;
  }

  /**
   * 分页查询成本补录单
   * @param search 查询条件
   * @return 成本补录单分页查询结果
   */
  @Override
  public Page<CostSupplementFormItemVo> pageSearch(
    CostSupplementFormSearchParamPo search
  ) {
    Page<CostSupplementFormItemVo> page = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return page;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return page;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    page = this.baseMapper.pageSearch(search.toPage(), search);
    List<Long> recordIds = page
      .getRecords()
      .stream()
      .map(CostSupplementFormItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return page;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return page;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    page
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });
    return page;
  }

  /**
   * 通用方法，为列表添加子表数据
   * @param pageResult 列表结果
   */
  protected Page<?> appendWithChild(Page<CostSupplementFormItemVo> pageResult) {
    return appendWithChild(pageResult, null);
  }

  /**
   * 通用方法，为列表添加子表数据
   * @param pageResult 列表结果
   * @param sort 子表排序
   */
  protected Page<?> appendWithChild(
    Page<CostSupplementFormItemVo> pageResult,
    String sort
  ) {
    Page<JSONObject> withChildPage = new Page<>(
      pageResult.getCurrent(),
      pageResult.getSize(),
      pageResult.getTotal()
    );
    withChildPage.setRecords(new ArrayList<>());

    CostSupplementFormSubtableSearchParamPo supplementaryProductSearchParamPo =
      new CostSupplementFormSubtableSearchParamPo();
    supplementaryProductSearchParamPo.setSort(sort);
    supplementaryProductSearchParamPo.setPageSize(200);
    supplementaryProductSearchParamPo.setParentCostSupplementFormInList(
      pageResult
        .getRecords()
        .stream()
        .map(CostSupplementFormItemVo::getId)
        .collect(Collectors.toList())
    );

    Map<String, Page<CostSupplementFormSubtableItemVoPages>> supplementaryProductMaps =
      costSupplementFormSubtableService.pagesByParentCostSupplementForm(
        supplementaryProductSearchParamPo
      );

    for (CostSupplementFormItemVo itemVo : pageResult.getRecords()) {
      JSONObject itemJson = (JSONObject) JSONObject.toJSON(itemVo);
      itemJson.put(
        "supplementaryProduct",
        supplementaryProductMaps.get(itemVo.getId().toString())
      );
      withChildPage.getRecords().add(itemJson);
    }
    return withChildPage;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return 成本补录单分页查询结果
   */
  @Override
  public Page<?> pageWithChildSearch(CostSupplementFormSearchParamPo search) {
    return appendWithChild(
      pageSearch(search),
      search.toChildSort("supplementaryProduct")
    );
  }

  /**
   * 仅获取子表的查询结果
   * @param parentId 主表编号
   * @param search 查询条件(仅使用分页参数，不处理其它条件)
   * @return
   */
  @Override
  public Page<?> pageOnlyChildSearch(
    Long parentId,
    CostSupplementFormSearchParamPo search
  ) {
    CostSupplementFormSearchParamPo parentSearchParam =
      new CostSupplementFormSearchParamPo();
    parentSearchParam.setIdEq(parentId);
    List<CostSupplementFormItemVo> parentList = search(parentSearchParam);
    if (parentList.size() > 0) {
      CostSupplementFormItemVo itemVo = parentList.get(0);

      CostSupplementFormSubtableSearchParamPo supplementaryProductSearchParamPo =
        new CostSupplementFormSubtableSearchParamPo();
      supplementaryProductSearchParamPo.setPageSize(search.getPageSize());
      supplementaryProductSearchParamPo.setCurrent(search.getCurrent());
      supplementaryProductSearchParamPo.setParentCostSupplementForm(
        itemVo.getId()
      );
      return costSupplementFormSubtableService.pageSearch(
        supplementaryProductSearchParamPo
      );
    } else {
      return null;
    }
  }

  /**
   * 成本补录单快速查询选项(有缓存)
   * @param search 查询条件
   * @return 选项结果
   */
  @Override
  @Cacheable(
    value = CacheConfig.FAST,
    key = "'CostSupplementFormOptions::' + @userInfo.userTypeAndId + '::' + #search.keyword"
  )
  public List<OptionItem<CostSupplementFormItemVo>> searchOptions(
    CostSupplementFormSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.searchOptions(search);
  }

  /**
   * 列表查询成本补录单
   * @param search 查询条件
   * @return 成本补录单列表查询结果
   */
  @Override
  public List<CostSupplementFormItemVo> search(
    CostSupplementFormSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.search(search);
  }

  /**
   * 查询成本补录单最后更新时间
   * @param search 查询条件
   * @return 成本补录单最后更新时间
   */
  @Override
  public Date searchLastUpdateTime(CostSupplementFormSearchParamPo search) {
    return this.baseMapper.searchLastUpdateTime(search);
  }

  /**
   * 操作
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了操作操作"
  )
  @Override
  public void handle(Long id) throws Exception {
    if (costSupplementFormHandleAction == null) {
      throw new Exception("此操作当前不可用");
    }
    costSupplementFormHandleAction.run(id);
  }

  /**
   * 添加成本补录单
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了添加成本补录单操作"
  )
  @Override
  public void addCostSupplementForm() throws Exception {
    if (costSupplementFormAddCostSupplementFormAction == null) {
      throw new Exception("此操作当前不可用");
    }
    costSupplementFormAddCostSupplementFormAction.run();
  }

  /**
   * 审批
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了审批操作"
  )
  @Override
  public void examineAndApprove() throws Exception {
    if (costSupplementFormExamineAndApproveAction == null) {
      throw new Exception("此操作当前不可用");
    }
    costSupplementFormExamineAndApproveAction.run();
  }

  /**
   * 删除
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了删除操作"
  )
  @Override
  public void delete1() throws Exception {
    if (costSupplementFormDelete1Action == null) {
      throw new Exception("此操作当前不可用");
    }
    costSupplementFormDelete1Action.run();
  }

  /**
   * 全部
   */
  @Override
  public List<CostSupplementFormItemVo> vAll(
    CostSupplementFormSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.vAll(search);
  }

  /**
   * 全部分页
   */
  @Override
  public Page<CostSupplementFormItemVo> vAllPage(
    CostSupplementFormSearchParamPo search
  ) {
    Page<CostSupplementFormItemVo> vAllPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return vAllPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return vAllPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    vAllPage = this.baseMapper.vAllPage(search.toPage(), search);
    List<Long> recordIds = vAllPage
      .getRecords()
      .stream()
      .map(CostSupplementFormItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return vAllPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return vAllPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    vAllPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return vAllPage;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return 成本补录单分页查询结果
   */
  @Override
  public Page<?> vAllPageWithChildSearch(
    CostSupplementFormSearchParamPo search
  ) {
    return appendWithChild(
      vAllPage(search),
      search.toChildSort("supplementaryProduct")
    );
  }

  /**
   * 查询全部最后更新时间
   * @param search 查询条件
   * @return 全部最后更新时间
   */
  @Override
  public Date vAllLastUpdateTime(CostSupplementFormSearchParamPo search) {
    return this.baseMapper.vAllLastUpdateTime(search);
  }

  /**
   * 待审批
   */
  @Override
  public List<CostSupplementFormItemVo> vApprove(
    CostSupplementFormSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.vApprove(search);
  }

  /**
   * 待审批分页
   */
  @Override
  public Page<CostSupplementFormItemVo> vApprovePage(
    CostSupplementFormSearchParamPo search
  ) {
    Page<CostSupplementFormItemVo> vApprovePage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return vApprovePage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return vApprovePage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    vApprovePage = this.baseMapper.vApprovePage(search.toPage(), search);
    List<Long> recordIds = vApprovePage
      .getRecords()
      .stream()
      .map(CostSupplementFormItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return vApprovePage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return vApprovePage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    vApprovePage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return vApprovePage;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return 成本补录单分页查询结果
   */
  @Override
  public Page<?> vApprovePageWithChildSearch(
    CostSupplementFormSearchParamPo search
  ) {
    return appendWithChild(
      vApprovePage(search),
      search.toChildSort("supplementaryProduct")
    );
  }

  /**
   * 查询待审批最后更新时间
   * @param search 查询条件
   * @return 待审批最后更新时间
   */
  @Override
  public Date vApproveLastUpdateTime(CostSupplementFormSearchParamPo search) {
    return this.baseMapper.vApproveLastUpdateTime(search);
  }

  /**
   * 已处理
   */
  @Override
  public List<CostSupplementFormItemVo> vDone(
    CostSupplementFormSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.vDone(search);
  }

  /**
   * 已处理分页
   */
  @Override
  public Page<CostSupplementFormItemVo> vDonePage(
    CostSupplementFormSearchParamPo search
  ) {
    Page<CostSupplementFormItemVo> vDonePage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return vDonePage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return vDonePage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    vDonePage = this.baseMapper.vDonePage(search.toPage(), search);
    List<Long> recordIds = vDonePage
      .getRecords()
      .stream()
      .map(CostSupplementFormItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return vDonePage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return vDonePage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    vDonePage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return vDonePage;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return 成本补录单分页查询结果
   */
  @Override
  public Page<?> vDonePageWithChildSearch(
    CostSupplementFormSearchParamPo search
  ) {
    return appendWithChild(
      vDonePage(search),
      search.toChildSort("supplementaryProduct")
    );
  }

  /**
   * 查询已处理最后更新时间
   * @param search 查询条件
   * @return 已处理最后更新时间
   */
  @Override
  public Date vDoneLastUpdateTime(CostSupplementFormSearchParamPo search) {
    return this.baseMapper.vDoneLastUpdateTime(search);
  }

  /**
   * 已驳回
   */
  @Override
  public List<CostSupplementFormItemVo> vReject(
    CostSupplementFormSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.vReject(search);
  }

  /**
   * 已驳回分页
   */
  @Override
  public Page<CostSupplementFormItemVo> vRejectPage(
    CostSupplementFormSearchParamPo search
  ) {
    Page<CostSupplementFormItemVo> vRejectPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return vRejectPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return vRejectPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    vRejectPage = this.baseMapper.vRejectPage(search.toPage(), search);
    List<Long> recordIds = vRejectPage
      .getRecords()
      .stream()
      .map(CostSupplementFormItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return vRejectPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return vRejectPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    vRejectPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return vRejectPage;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return 成本补录单分页查询结果
   */
  @Override
  public Page<?> vRejectPageWithChildSearch(
    CostSupplementFormSearchParamPo search
  ) {
    return appendWithChild(
      vRejectPage(search),
      search.toChildSort("supplementaryProduct")
    );
  }

  /**
   * 查询已驳回最后更新时间
   * @param search 查询条件
   * @return 已驳回最后更新时间
   */
  @Override
  public Date vRejectLastUpdateTime(CostSupplementFormSearchParamPo search) {
    return this.baseMapper.vRejectLastUpdateTime(search);
  }
}
